package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"time"
)

type IpccSipUser struct {
	Id         int
	Account    string
	Password   string
	AppId      string
	Active     bool
	CreateTime time.Time `orm:"auto_now_add; type(datetime)"`
}

func RegisterSipUser() {
	orm.RegisterModel(new(IpccSipUser))
}

func GetSipUser(account string) (IpccSipUser, error) {

	result := IpccSipUser{
		Account: account,
		Active:  true,
	}
	o := orm.NewOrm()
	err := o.QueryTable(new(IpccSipUser)).Filter("Account", account).Filter("Active", true).One(&result)
	if err != nil {
		logs.Error("query %v from sql err:%v", account, err)
		return IpccSipUser{}, err
	}

	return result, nil
}

func AddNewSipUser(account, appId, passwd string) error {

	newAcct := IpccSipUser{
		Account:  account,
		Active:   true,
		AppId:    appId,
		Password: passwd,
	}

	o := orm.NewOrm()
	create, _, err := o.ReadOrCreate(&newAcct, "Account")
	if err == nil {
		if !create {
			return fmt.Errorf("%v is exist", account)
		}
	} else {
		logs.Error("add sip user err:%v", err)
		return err
	}

	return nil
}

func UpdateSipUser(account, passwd string, active bool) error {

	newAcct := IpccSipUser{
		Account:  account,
		Active:   active,
		Password: passwd,
	}

	o := orm.NewOrm()
	_, err := o.Update(&newAcct, "Account")
	return err
}
